package org.example.smart.server;

import com.briup.smart.env.entity.Environment;
import com.briup.smart.env.server.DBStore;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;

public class DBStoreImpl implements DBStore {
    @Override
    public void saveDB(Collection<Environment> collection) throws Exception {
        String driverClass = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/env";
        String username = "root";
        String password = "root1234";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            Class.forName(driverClass);
            conn = DriverManager.getConnection(url, username, password);
            conn.setAutoCommit(false);
            String sql = "insert into e_detail_1(name,srcId,desId,devId,sersorAddress,count,cmd,status,data,gather_Date) values(?,?,?,?,?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            for (Environment e :
                    collection) {
                pstmt.setString(1,e.getName());
                pstmt.setString(2,e.getSrcId());
                pstmt.setString(3,e.getDesId());
                pstmt.setString(4,e.getDevId());
                pstmt.setString(5,e.getSensorAddress());
                pstmt.setInt(6,e.getCount());
                pstmt.setString(7,e.getCmd());
                pstmt.setInt(8,e.getStatus());
                pstmt.setFloat(9,e.getData());
                pstmt.setTimestamp(10,e.getGatherDate());
                pstmt.addBatch();
                pstmt.executeBatch();
                conn.commit();
            }
            System.out.println("服务端成功将数据放入数据库中");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
